#ifndef NETWROKUTILS_H
#define NETWROKUTILS_H

#include <QObject>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QNetworkRequest>
#include <QJsonDocument>
#include <QJsonObject>
#include <QEventLoop>
#include <QTimer>

class NetwrokUtils : public QObject
{
    Q_OBJECT
public:
    explicit NetwrokUtils(QObject *parent = nullptr);
    ~NetwrokUtils();

    // 设置MES服务器地址
    void setServerUrl(const QString &url);

    // 设置认证信息
    void setAuthInfo(const QString &username, const QString &password);

    // 设置超时时间(毫秒)
    void setTimeout(int milliseconds);

    // 同步发送请求
    bool sendRequestSync(const QString &endpoint,
                         const QJsonObject &requestData,
                         QJsonObject &responseData,
                         QString &errorString);

    // 异步发送请求
    void sendRequestAsync(const QString &endpoint,
                          const QJsonObject &requestData);

signals:
    // 异步请求完成信号
    void requestCompleted(const QJsonObject &responseData);
    // 异步请求错误信号
    void requestError(const QString &errorString);

private slots:
    void onReplyFinished(QNetworkReply *reply);
    void onTimeout();

private:
    QNetworkAccessManager *m_networkManager;
    QString m_serverUrl;
    QString m_username;
    QString m_password;
    int m_timeout;
    QTimer m_timer;
    QNetworkReply *m_currentReply;
    bool m_isSyncRequest;
    QEventLoop *m_eventLoop;
    QJsonObject m_syncResponse;
    QString m_syncError;
    bool m_requestSuccess;

    // 创建请求
    QNetworkRequest createRequest(const QString &endpoint);

    // 处理响应
    void processReply(QNetworkReply *reply);
};

#endif // NETWROKUTILS_H
